package com.huang.readwriteLock;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/*          总结：
                    sync和ReentrantLock
                                读读，写写，读写都 独占只允许一个线程操作
                    ReentrantReadWriteLock  读写锁：
                                读可共享可多人一起读  写独占只允许一个线程写
                                 缺点：  写锁会产生锁饥饿问题  写锁迟迟回去不到锁


*
*
*
*
* */
class Myresourse{
    private Map<String,String> map=new HashMap();
    private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();

    public void read(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"...在读");
            map.get(key);

            System.out.println(Thread.currentThread().getName()+"...读完");

        } finally {
            lock.readLock().unlock();
        }

    }
    public void write(String key,String value){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "...在写");

            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "...写完");

        } finally {
            lock.writeLock().unlock();
        }
    }



}
public class demo {
    public static void main(String[] args) {
        Myresourse myresourse = new Myresourse();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                myresourse.write("read","write");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                myresourse.read("read");

            },String.valueOf(i)).start();
        }

    }
}
